#include "FileHandler.hpp"
#include <iostream>

#ifdef _WIN32
#include <windows.h>
#include <commdlg.h>
#endif
_NNU_DGGS_BEGIN
namespace DGGSViewer
{
    FileHandler::FileHandler() = default;

    FileHandler::~FileHandler() = default;

    std::string FileHandler::showOpenFileDialog()
    {
        std::string filePath;

#ifdef _WIN32
        OPENFILENAMEA ofn;
        char szFile[260] = {0};

        ZeroMemory(&ofn, sizeof(ofn));
        ofn.lStructSize = sizeof(ofn);
        ofn.hwndOwner = nullptr;
        ofn.lpstrFile = szFile;
        ofn.nMaxFile = sizeof(szFile);
        ofn.lpstrFilter = "GeoJSON Files\0*.geojson\0TIFF Files\0*.tiff;*.tif\0All Files\0*.*\0";
        ofn.nFilterIndex = 1;
        ofn.lpstrFileTitle = nullptr;
        ofn.nMaxFileTitle = 0;
        ofn.lpstrInitialDir = nullptr;
        ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

        if (GetOpenFileNameA(&ofn))
        {
            filePath = ofn.lpstrFile;
        }
#endif

        return filePath;
    }

    std::vector<std::string> FileHandler::showOpenMultipleFilesDialog()
    {
        std::vector<std::string> filePaths;

#ifdef _WIN32
        OPENFILENAMEA ofn;
        char szFile[8192] = {0}; // 增大缓冲区以容纳多个文件路径

        ZeroMemory(&ofn, sizeof(ofn));
        ofn.lStructSize = sizeof(ofn);
        ofn.hwndOwner = nullptr;
        ofn.lpstrFile = szFile;
        ofn.nMaxFile = sizeof(szFile);
        ofn.lpstrFilter = "GeoJSON Files\0*.geojson\0TIFF Files\0*.tiff;*.tif\0All Files\0*.*\0";
        ofn.nFilterIndex = 1;
        ofn.lpstrFileTitle = nullptr;
        ofn.nMaxFileTitle = 0;
        ofn.lpstrInitialDir = nullptr;
        ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER;

        if (GetOpenFileNameA(&ofn))
        {
            // 获取包含文件路径的缓冲区
            char* p = ofn.lpstrFile;
            
            // 第一个字符串是目录路径
            std::string directory = p;
            p += directory.length() + 1;
            
            // 检查是否选择了多个文件
            if (*p)
            {
                // 多个文件情况：第一个字符串是目录，后面的字符串是文件名
                while (*p)
                {
                    std::string filename = p;
                    std::string fullPath = directory + "\\" + filename;
                    filePaths.push_back(fullPath);
                    p += filename.length() + 1;
                }
            }
            else
            {
                // 单个文件情况：缓冲区只包含完整路径
                filePaths.push_back(directory);
            }
        }
#endif

        return filePaths;
    }
}

_NNU_DGGS_END
